package com.limewoodMedia.djurvanligt.util;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import com.limewoodMedia.djurvanligt.Djurvanligt;
import com.limewoodMedia.djurvanligt.R;
import com.limewoodMedia.djurvanligt.list.DVListActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.widget.Toast;

public class UpdateChecker extends AsyncTask<String, Integer, Boolean> {
	private Djurvanligt context;
	private ProgressDialog dialog;
	
	public UpdateChecker(Djurvanligt context, ProgressDialog dialog) {
		this.context = context;
		this.dialog = dialog;
	}
	
	@Override
	protected Boolean doInBackground(String... param) {
		boolean updated = false;
		
		/* General data file || E-number file */
		updated = updateDataFile(Djurvanligt.DATA_BASE, "basicData", param[0])
			| updateDataFile(Djurvanligt.E_BASE, "eData", param[1]);
		
		return updated;
	}
	
	private boolean updateDataFile(String fileName, String prefName, String urlStr) {
		try {
			// Get last modified date of local file from saved preferences
			SharedPreferences prefs = Djurvanligt.appContext.getSharedPreferences("DataLastModified", 0);
			long localModified = prefs.getLong(prefName, 0);
			System.out.println("local "+localModified);
			
			// Get last modified date of network file
			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			long networkModified = conn.getLastModified();
			System.out.println("network "+networkModified);
			
			if(networkModified > localModified) {
				// Update file
				conn.connect();
	
	            // Download the file
	            InputStream input = new BufferedInputStream(url.openStream());
	            OutputStream output = context.openFileOutput(fileName, Context.MODE_PRIVATE);
	            int len = conn.getContentLength();
	
	            byte data[] = new byte[1024];
	            int count;
	            long total = 0;
	
	            while ((count = input.read(data)) != -1) {
	            	total += count;
	            	publishProgress((int)(total*100/len));
	                output.write(data, 0, count);
	            }
	
	            output.flush();
	            output.close();
	            input.close();
	            
	            // Update last updated time
	            SharedPreferences.Editor editor = prefs.edit();
	            editor.putLong(prefName, networkModified);
	            editor.commit();
	            
	            return true;
			}
			else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	@Override
	protected void onProgressUpdate(Integer... values) {
		if(!dialog.isShowing() && Djurvanligt.active == context) {
			// Show progress dialog
        	dialog.show();
		}
		dialog.setProgress(values[0]);
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		// Show that the data has been updated
		if(result) {
			if(Djurvanligt.active != null) {
				// If we are in one of the lists, give the option to restart
				if(Djurvanligt.active instanceof DVListActivity) {
					new AlertDialog.Builder(Djurvanligt.active)
			        	.setIcon(android.R.drawable.ic_dialog_alert)
			        	.setTitle(context.getString(R.string.update_dialog_title))
			        	.setMessage(context.getString(R.string.update_dialog_text))
			        	.setPositiveButton(context.getString(R.string.update_dialog_confirm), new DialogInterface.OnClickListener() {
				            @Override
				            public void onClick(DialogInterface dialog, int which) {
				                //Stop the activity
				            	Activity temp = Djurvanligt.active;
				                temp.finish();
				                context.startActivity(new Intent(context, temp.getClass()));
				            }
			        	})
			        	.setNegativeButton(context.getString(R.string.update_dialog_cancel), null)
			        	.show();
				}
				else {
					Toast t = Toast.makeText(context, context.getString(R.string.update_notification_text), Toast.LENGTH_LONG);
					t.show();
				}
			}
			else {
				String ns = Context.NOTIFICATION_SERVICE;
				NotificationManager notificationManager = (NotificationManager) context.getSystemService(ns);

				int icon = R.drawable.icon;
				CharSequence tickerText = context.getString(R.string.update_notification_title);
				long when = System.currentTimeMillis();

				Notification notification = new Notification(icon, tickerText, when);
				notification.flags = Notification.FLAG_AUTO_CANCEL;

				CharSequence contentTitle = context.getString(R.string.update_notification_title);
				CharSequence contentText = context.getString(R.string.update_notification_text);
				Intent notificationIntent = new Intent(context, Djurvanligt.class);
				PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

				notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

				notificationManager.notify(1, notification);
			}
		}
		dialog.dismiss();
	}
}
